import { RouteLocationNormalized } from 'vue-router';
import { SaaSPageEnum } from '/@/enums/pageEnum';
import { RootRoute } from '../routes';
import { usePermissionStoreWithOut } from '/@/store/modules/permission';
import { getToken } from '../../hooks/globVar/index';

const LOGIN_PATH = SaaSPageEnum.BASE_LOGIN;
const MEDIA_PATH = SaaSPageEnum.MEDIA_PATH;
const PLATFORM_HOME_PATH = SaaSPageEnum.PLATFORM_HOEMPAGE;
const TENANT_HOME_PATH = SaaSPageEnum.TENANT_HOMEPAGE;
const INSTANCE_PURCHASE_PATH = SaaSPageEnum.INSTANCE_PURCHASE;
const MONO_MEDIA_PATH = SaaSPageEnum.MONO_MEDIA_PATH;
const ROOT_PATH = RootRoute.path;

const permissionStore = usePermissionStoreWithOut();

type StrategyFunc = (to: RouteLocationNormalized, from: RouteLocationNormalized) => boolean;

// true 直接放行， false 需要刷新菜单
const strategy: StrategyFunc[] = [
  function alreadyDynamicAddedRoute(): boolean {
    // 跳转集成不需要请求菜单
    return permissionStore.getDynamicAddedRoute;
  },
  function rootToMono(to: RouteLocationNormalized): boolean {
    // 跳转集成不需要请求菜单
    return to.path === MONO_MEDIA_PATH ? true : false;
  },
  function jumpToLoginWithoutToken(to: RouteLocationNormalized): boolean {
    // 带着登录信息跳转
    const token = getToken();
    return to.path === LOGIN_PATH && !token ? true : false;
  },

  function rootToMeida(to: RouteLocationNormalized, from: RouteLocationNormalized): boolean {
    // 点击应用卡片无需多余请求菜单
    return from.path === ROOT_PATH && to.path === MEDIA_PATH ? true : false;
  },

  function loginToMedia(to: RouteLocationNormalized, from: RouteLocationNormalized): boolean {
    // 从根路径直接跳转至中间页
    return from.path === LOGIN_PATH && to.path === MEDIA_PATH ? true : false;
  },

  function mediaToHomepage(to: RouteLocationNormalized, from: RouteLocationNormalized): boolean {
    // 从根路径直接跳转至中间页
    return from.path === MEDIA_PATH &&
      (to.path === PLATFORM_HOME_PATH + '/index' ||
        to.path === TENANT_HOME_PATH + '/index' ||
        to.path === INSTANCE_PURCHASE_PATH + '/index')
      ? true
      : false;
  },
];

class Validator {
  strategy: StrategyFunc[];
  constructor() {
    this.strategy = strategy;
  }
  start(to: RouteLocationNormalized, from: RouteLocationNormalized) {
    for (let i = 0; i < this.strategy.length; i++) {
      if (this.strategy[i](to, from)) {
        return true;
      }
    }
    return false;
  }
}

export { Validator };
